package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.ItemComment;
import cn.wolfcode.luowowo.comment.query.ItemCommentQuery;
import cn.wolfcode.luowowo.comment.repository.ItemCommentRepository;
import cn.wolfcode.luowowo.comment.service.IItemCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;

@Service
public class ItemCommentServiceImpl implements IItemCommentService {
    @Autowired
    private ItemCommentRepository repository;
    @Autowired
    private MongoTemplate template;

    @Override
    public void save(ItemComment comment) {
        comment.setCreateTime(new Date());
        if(comment.getState() == 1){
            String content = comment.getContent();
            int i = content.indexOf(":");
            comment.setContent(content.substring(i+1));
        }
        repository.save(comment);
    }

    @Override
    public Page query(ItemCommentQuery qo) {
        //查询总条数
        Query query = new Query();
        long count = template.count(query, ItemComment.class);
        if(count == 0){
            return Page.empty();
        }
        //查询list集合
        PageRequest pageRequest = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC,"createTime");
        List<ItemComment> comments = template.find(query, ItemComment.class);
        return new PageImpl(comments,pageRequest,count);
    }
}
